package net.guerlab.smart.platform.user.service.service.impl;

import net.guerlab.smart.platform.commons.Constants;
import net.guerlab.smart.platform.server.service.BaseServiceImpl;
import net.guerlab.smart.platform.user.service.entity.LoginLog;
import net.guerlab.smart.platform.user.service.mapper.LoginLogMapper;
import net.guerlab.smart.platform.user.service.service.LoginLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 登录记录服务实现
 *
 * @author guer
 */
@Service
public class LoginLogServiceImpl extends BaseServiceImpl<LoginLog, Long, LoginLogMapper> implements LoginLogService {

    @Override
    @Async
    public void addSuccessLog(Long userId, String name, String loginIdentity, String loginType, String loginIp) {
        addLog(userId, name, loginIdentity, loginType, loginIp, true, Constants.EMPTY_NAME);
    }

    @Override
    @Async
    public void addFailLog(Long userId, String name, String loginIdentity, String loginType, String loginIp,
            String reason) {
        addLog(userId, name, loginIdentity, loginType, loginIp, false, StringUtils.trimToEmpty(reason));
    }

    private void addLog(Long userId, String name, String loginIdentity, String loginType, String loginIp,
            boolean success, String reason) {
        LoginLog entity = new LoginLog();
        entity.setLoginLogId(sequence.nextId());
        entity.setUserId(userId);
        entity.setName(name);
        entity.setLoginIdentity(loginIdentity);
        entity.setLoginType(loginType);
        entity.setLoginIp(loginIp);
        entity.setLoginTime(LocalDateTime.now());
        entity.setSuccess(success);
        entity.setReason(reason);

        mapper.insert(entity);
    }
}
